//
//  TempLovExtesion.swift
//  ANOA
//
//  Created by 邱仙凯 on 2023/7/12.
//  Copyright © 2023 zwb. All rights reserved.
//  lov   下拉选    跟随接口

import UIKit

extension ConfigMenuForm  {
  
    
    // MARK:   url 和下拉选   有后续接口，继续调用  scanRest 外面给的扫码结果，有了就不用再扫了
    func continueUrl(onexx:TemplateModel,indexPath:IndexPath? = nil,scanRest:String = "") {
        
        // 有后续接口就 继续调用后续接口
        if onexx.call_port_url.unwrap != "" {
            TempLog("\n\n\n调用跟随接口")
          
           
            
            
            let pathArrs = url2PathOriParam(onexx.call_port_url.unwrap)
            var detDic:[String:Any]?
            if indexPath.isSome {
                detDic = self.detHandler[self.cDIndex][indexPath!.section].dic
            }
            var pathDic = url2PathDic(mainDic: self.main,currDetaiDic: detDic,arr: pathArrs.comPa)
            let scanArr = pathArrs.spePa.filter { $0.contains("scanResult") }
            if scanRest != "" {
                // 外面带了扫码结果
                let scanKey = scanArr.first!.preChar(char: "=").unwrap
                pathDic.updateValue(scanRest, forKey: scanKey)
                startNet()
            } else {
                if scanArr.count > 0 {
                    SwiftScanHelper.shared.openScan(controller:self) { rst in
                        let scanKey = scanArr.first!.preChar(char: "=").unwrap
                        pathDic.updateValue(rst, forKey: scanKey)
                        startNet()
                    }
                } else {
                    startNet()
                }
            }
            
            func startNet() {
                TempLog(pathArrs.path)
            
                KSNetwork.shared.doRequest(API.temp(.path(path: pathArrs.path, paramDic: pathDic))) { (data:BaseResult<OperateResult>) in
                    if data.flag == TRUE {
                        
                        // 执行型的事件 弹出提示即结束
                       guard onexx.field_type != TemplateType.btnevent_exec.rawValue else {
                            KSToast(data.errorCombine.unwrap)
                           return
                        }
                        let callpbFill = onexx.callInterfaceBackArr
                        // 返回了数组
                        let infos = data.infoDicArr
                        self.dealFill(backFillArr: callpbFill, indexPath: indexPath,infos: infos,infoDic: data.infoDic)

                       
                    
                 
                        
                    } else {
                        KSToast(data.errorCombine.unwrap)
                    }
                }
            }
            
            
            
            
        }
    }
    // lov 和 continueurl 共用的回填处理办法  多选
    func dealFill(backFillArr:[String],indexPath:IndexPath? = nil,infos:[[String:Any]],infoDic:[String:Any]?) {
      
        var aDealA = [String]()
        var bDealA = [BackFillStruct]()
         
            for item in backFillArr {
                let pr = item.preChar(char: ":").unwrap

                let sf = item.sufChar(char: ":").unwrap
                let sf_pr = sf.preChar(char: ".").unwrap // a   b   detail invoice
                let sf_sf = sf.sufChar(char: ".").unwrap

                if sf_pr == "a" {
                    aDealA.append(item)
                } else if sf_pr == "" {
               
                    if  indexPath.isSome {
                        bDealA.append(BackFillStruct(fromParam: pr,toParam: sf,detFlag: "b."))
                    } else {
                        aDealA.append(item)
                    }
 
                    
                } else {
                     bDealA.append(BackFillStruct(fromParam: pr,toParam: sf_sf,detFlag: sf_pr))
                 }
                 
            }
       
  
        if infos.count > 0 {
            // 有主表回填
            if aDealA.count > 0 {
                
                 
                
                for item in aDealA {
                    let pre = item.preChar(char: ":").unwrap
                    var realKey = item.sufChar(char: ":").unwrap
                    realKey = realKey.replacingOccurrences(of: "a.", with: "")
                    
                    var vvAA = [String]()
                    for yy in 0..<infos.count {
                        let dicc = infos[yy]
                         vvAA.append(any2Str(dicc[pre]))
                      }
                    var dealedValue = vvAA.joined(separator:",")
                     
                    self.main[realKey] = dealedValue
                }
             
                
                self.configTempDataSource()
            }
            
            // 有细表回填
            if bDealA.count > 0 {
          
                if indexPath.isSome {
                    
                    self.backFillDetself(infos.first!,indexPath: indexPath,bDealA: bDealA)
                    self.configTempDataSource()
                 } else {
                    // 主表事件的细表回填，直接覆盖细表
                     self.backFillAllDetail(infos,bDealA: bDealA)
                    self.configTempDataSource()
                    self.activeDetailRow(indexx: 0,status: "true",scroll: false)
                }
            
                
            }
            
        }
        
        
        
        // 返回了单个对象
        if let infoD = infoDic {
            
            if aDealA.count > 0 {
                for item in aDealA {
                    let pre = item.preChar(char: ":").unwrap
                    var realKey = item.sufChar(char: ":").unwrap
                    realKey = realKey.replacingOccurrences(of: "a.", with: "")
                    self.main[realKey] = infoD[pre]
                }
                self.configTempDataSource()
            }
            if bDealA.count > 0 {
                
                // 获取细表的回填
                if let det = infoD[TKey.details] as? [[String:Any]] {
                    
                    // 主表事件的细表回填，直接覆盖细表
                    self.backFillAllDetail(det,bDealA: bDealA)
                    self.configTempDataSource()
                    self.activeDetailRow(indexx: 0,status: "true",scroll: false)
                } else {
                    // 细表自己回填自己
                    self.backFillDetself(infoD,indexPath: indexPath,bDealA: bDealA)
                    self.configTempDataSource()
                 }
            }
        }
    }
    func backFillDetself(_ dataDic:[String:Any],indexPath:IndexPath?,bDealA:[BackFillStruct]) {
        // 细表事件的细表回填，回填本身这一条
        TempLog("\n\n细表回填自身--")
        
        for curr in bDealA {
 
            let val = dataDic[curr.fromParam]
            TempLog("\(curr.fromParam)-->\(curr.toParam) 值:\(val.unwrap)")
            self.detHandler[self.cDIndex][indexPath!.section].dic[curr.toParam] = val
        }
    }
    // 主表事件的细表回填，直接覆盖细表
    func backFillAllDetail(_ infos: [[String : Any]],bDealA:[BackFillStruct]) {
        TempLog("\n\n细表覆盖式回填--\n")
        
         var currInd = 0
        if let iid = self.rootTemp.multiDetailsParams.getIndexFor({ onex in
            onex == bDealA.first!.detFlag
        }) {
            currInd = iid
        }
        
        self.detHandler[currInd].removeAll()
        self.oriDetArr[currInd].removeAll()
        
        for x in 0..<infos.count {
            var det = temp2Dic(self.tempDet[currInd],rootTemp: rootTemp)
            
           
            for y in 0..<bDealA.count {
                let curr = bDealA[y]
             
                 TempLog("\(curr.toParam)-----》值\(infos[x][curr.fromParam])")
                 det[curr.toParam] = infos[x][curr.fromParam]
                
            }
            self.detHandler[currInd].append(DetailsTempCom(temp: self.tempDet[currInd], dic: det))
         
        }
        
        
       
        
       
        
    }
    
    
}
